package com.meteor.raft.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.meteor.raft.core.RaftCore;
import com.meteor.raft.core.RaftPeerManage;
import com.meteor.raft.healthcheck.HealthCheckService;
import com.meteor.raft.masterelection.ElectionService;
import com.meteor.raft.misc.WebUtils;
import com.meteor.raft.persistent.RaftPeer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author gang.wang1903@xiaobao100.cn
 * @Date: 2019/7/19 10:36 AM
 */
@RestController
@RequestMapping("/meteorRaft/raft")
@Slf4j
public class RaftController {

    @Autowired
    private ElectionService electionService;

    @Autowired
    private HealthCheckService healthCheckService;


    @PostMapping("/vote")
    public JSONObject vote(HttpServletRequest request, HttpServletResponse response) {
        RaftPeer peer = electionService.receivedVote(
                JSON.parseObject(WebUtils.required(request, "vote"), RaftPeer.class));

        return JSON.parseObject(JSON.toJSONString(peer));
    }

    @PostMapping("/beat")
    public JSONObject beat(HttpServletRequest request, HttpServletResponse response) {
        log.error("[RAFT] get  heart beat ");
        RaftPeer peer = healthCheckService.receivedBeat(
                JSON.parseObject(WebUtils.required(request, "beat"), RaftPeer.class));
        return JSON.parseObject(JSON.toJSONString(peer));
    }
}

